package com.example.cloud.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.jdbc.core.JdbcTemplate;

import jakarta.annotation.PostConstruct;

@Slf4j
@Component
public class DatabaseInitializer {

    private final JdbcTemplate jdbcTemplate;

    @Value("${spring.datasource.url}")
    private String dbUrl;

    public DatabaseInitializer(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @PostConstruct
    public void initialize() {
        try {
            // 测试数据库连接
            Integer result = jdbcTemplate.queryForObject("SELECT 1", Integer.class);
            log.info("数据库连接测试成功: {}", result);
            
            // 获取数据库版本信息
            String version = jdbcTemplate.queryForObject("SELECT VERSION()", String.class);
            log.info("MySQL 版本: {}", version);
            
            // 获取当前数据库名
            String dbName = jdbcTemplate.queryForObject("SELECT DATABASE()", String.class);
            log.info("当前数据库: {}", dbName);
            
            log.info("数据库初始化成功");
        } catch (Exception e) {
            log.error("数据库初始化失败", e);
            // 不抛出异常，允许应用程序继续启动
            // throw new RuntimeException("数据库初始化失败", e);
        }
    }
} 